package com.daervin.svc.service.impl;

import com.daervin.svc.common.constants.Constants;
import com.daervin.svc.common.constants.ImageType;
import com.daervin.svc.common.dto.img.ImgItemDTO;
import com.daervin.svc.common.dto.img.PixabayImgDTO;
import com.daervin.svc.common.utils.DateTimeUtils;
import com.daervin.svc.common.utils.FileUtil;
import com.daervin.svc.common.utils.JsonUtil;
import com.daervin.svc.dal.ImageDao;
import com.daervin.svc.dal.model.Image;
import com.daervin.svc.service.ImageService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class ImageServiceImpl implements ImageService {
    @Resource
    private ImageDao imageDao;

    @Override
    public List<String> queryByType(ImageType type) {
        return imageDao.queryByType(type.ordinal());
    }

    @Override
    public void synchronizePixabay() {
        try {
            Calendar now = Calendar.getInstance();
            String day = DateTimeUtils.longParse2(now.getTime());
            int dayOfMonth = now.get(Calendar.DAY_OF_MONTH);
            OkHttpClient httpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(Constants.IMAGE_PIXABAY + dayOfMonth)
                    .build();
            Response response = httpClient.newCall(request).execute();
            String descResponse = response == null || response.body() == null ? null : response.body().string();
            if (StringUtils.isEmpty(descResponse)) {
                return;
            }
            PixabayImgDTO imgDto = JsonUtil.toObject(descResponse, PixabayImgDTO.class);
            if (imgDto == null || CollectionUtils.isEmpty(imgDto.getHits())) {
                return;
            }
            if (dayOfMonth == 1) {
                Integer count = imageDao.deleteByType(ImageType.PIXABAY.ordinal());
                if (count != null && count > 0) {
                    FileUtil.dropAllFile(Constants.IMAGE_LOCALPATH);
                }
            }
            List<Image> list = new ArrayList<>();
            int sort = 1;
            for (ImgItemDTO item : imgDto.getHits()) {
                if (item.getLikes() == null || item.getLikes() < 10) {
                    continue;
                }
                Image po = new Image();
                po.setType(ImageType.PIXABAY.ordinal());
                String url = item.getWebformatURL().replace("_640", "_340");
                String imgName = new StringBuilder(day).append("-").append(sort).append(".jpg").toString();
                String localPath = Constants.IMAGE_LOCALPATH + imgName;
                String domainUrl = Constants.IMAGE_DOMAIN + imgName;
                boolean success = FileUtil.downloadSaveFile(url, localPath);
                if (!success) {
                    continue;
                }
                po.setUrl(domainUrl);
                po.setSort(sort++);
                list.add(po);
            }
            imageDao.insertBatch(list);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    @Override
    public void bannerImg(List<Image> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        imageDao.deleteByType(ImageType.HU_XIU.ordinal());
        imageDao.insertBatch(list);
    }
}
